package com.jeeplus.invoice.api;


import com.jeeplus.invoice.customer.service.YxfpCustomerService;
import com.jeeplus.invoice.customer.service.dto.YxfpCustomerDTO;
import com.jeeplus.invoice.customer.service.mapstruct.YxfpCustomerWrapper;
import com.jeeplus.invoice.merchant.service.YxfpMerchantService;
import com.jeeplus.invoice.merchant.service.dto.YxfpMerchantDTO;
import com.jeeplus.invoice.merchant.service.mapstruct.YxfpMerchantWrapper;
import com.jeeplus.invoice.utils.ResObject;
import com.jeeplus.invoice.utils.WechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "越香发票-微信相关接口API")
@RestController
@RequestMapping(value = "/invoice/api/wx")
public class WechatAPI {

    @Autowired
    private YxfpCustomerService yxfpCustomerService;

    @Autowired
    private YxfpCustomerWrapper yxfpCustomerWrapper;

    @Autowired
    private YxfpMerchantService yxfpMerchantService;

    @Autowired
    private YxfpMerchantWrapper yxfpMerchantWrapper;

    /**
     * 根据微信code获取用户openId,并判断是否存在该用户，若存在返回该用户，否则新生成用户
     * @param code 微信code
     * @return
     */
    @ApiOperation(value = "根据微信code获取用户openId,并判断是否存在该用户，若存在返回该用户，否则新生成用户")
    @GetMapping("getUserInfo")
    public ResponseEntity<YxfpCustomerDTO> getUserInfo(String code) {
        String openId = WechatUtil.getOpenID(code);
        YxfpCustomerDTO userInfo = yxfpCustomerService.findByOpenId(openId);
        if(userInfo==null){
            userInfo = new YxfpCustomerDTO();
            userInfo.setOpenId(openId);
            yxfpCustomerService.saveOrUpdate(yxfpCustomerWrapper.toEntity(userInfo));
            userInfo = yxfpCustomerService.findByOpenId(openId);
        }
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 根据微信code获取商户openId,并判断是否存在该商户，若存在返回该商户，否则新生成商户
     * @param code
     * @return
     */
    @ApiOperation(value = "根据微信code获取商户openId,并判断是否存在该商户，若存在返回该商户，否则新生成商户")
    @GetMapping("getMerchantInfo")
    public ResponseEntity<YxfpMerchantDTO> getMerchantInfo(String code) {
        String openId = WechatUtil.getOpenID(code);
        YxfpMerchantDTO merchantInfo = yxfpMerchantService.findByOpenId(openId);
        if(merchantInfo==null){
            merchantInfo = new YxfpMerchantDTO();
            merchantInfo.setOpenId(openId);
            yxfpMerchantService.saveOrUpdate(yxfpMerchantWrapper.toEntity(merchantInfo));
            merchantInfo = yxfpMerchantService.findByOpenId(openId);
        }
        return ResponseEntity.ok(merchantInfo);
    }



}
